﻿using AVIS.OutBound.WizardAgent.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AVIS.OutBound.WizardAgent
{
    /// <summary>
    /// 车组增值服务的Wizard服务
    /// </summary>
    public class WizardVehRateRuleAgent
    {
        /// <summary>
        /// 获取指定SIPPCode和RateCode的单个车组信息（包含增值服务）的Wizard服务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public CarEquipmentResponse GetCarGroupWithEquipments(CarEquipmentRequest request)
        {
            // 检查请求参数是否正确
            request.CheckRequest();

            // 请求Wizard接口获取指定车型组的增值服务的Wizard服务（OTA_VehRateRule）
            var response = WizardCacheHelper.GetResponseXml<CarEquipmentResponse>(request, (xml) =>
            {
                return WizardHttpClient.PostXml(xml);
            });

            // 解析车组套餐的XML
            if (!response.HasError)
            {
                var responseXDoc = XDocument.Parse(response.ResponseString);
                response.Data = GetCarGroupFromXml(XmlHelpler.FindXElement(responseXDoc.Root, "OTA_VehRateRuleRS", WizardConsts.XNamespace));
            }

            return response;
        }

        #region 解析车辆装备的XML

        private CarGroupDto GetCarGroupFromXml(XElement parentXElement)
        {
            var xVehicle = XmlHelpler.FindXElement(parentXElement, "Vehicle", WizardConsts.XNamespace);
            var xRentalRate = XmlHelpler.FindXElement(parentXElement, "RentalRate", WizardConsts.XNamespace);
            var xTotalCharge = XmlHelpler.FindXElement(parentXElement, "TotalCharge", WizardConsts.XNamespace);
            var xPricedEquips = XmlHelpler.FindXElement(parentXElement, "PricedEquips", WizardConsts.XNamespace);
            var xPricedCoverages = XmlHelpler.FindXElement(parentXElement, "PricedCoverages", WizardConsts.XNamespace);
            var xReference = XmlHelpler.FindXElement(parentXElement, "Reference", WizardConsts.XNamespace);

            var carGroup = new CarGroupDto();
            carGroup.ParseVehicleXml(xVehicle);
            carGroup.ParseRentalRateXml(xRentalRate);
            carGroup.ParseTotalChargeXml(xTotalCharge);
            carGroup.ParsePricedEquipsXml(xPricedEquips);
            carGroup.ParsePricedCoveragesXml(xPricedCoverages);
            carGroup.ParseFeaturesReferenceXml(xReference);

            return carGroup;
        }

        #endregion
    }
}
